package com.atguigu.gmall.item.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.list.client.ListFeignClient;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


@RestController
@RequestMapping("/api/item")
public class ItemApiController {

    @Autowired
    ProductFeignClient productFeignClient;

    @Autowired
    ThreadPoolExecutor threadPool;

    @Autowired
    ListFeignClient listFeignClient;

    //数据汇总
    @GetMapping("/getItem/{skuId}")
    public Map<String,Object> getItem(@PathVariable Long skuId){
        Map<String,Object> map = new HashMap<>();


        CompletableFuture<SkuInfo> c1 = CompletableFuture.supplyAsync(() -> {
            //1、查询Sku中的信息
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
            map.put("skuInfo",skuInfo);
            return skuInfo;
        },threadPool);

        CompletableFuture<Void> c2 = c1.thenAcceptAsync(skuInfo -> {
            //2、查询一二三级分类
            BaseCategoryView baseCategoryView = productFeignClient.getBaseCategoryView(skuInfo.getCategory3Id());
            map.put("categoryView", baseCategoryView);
        }, threadPool);

        CompletableFuture<Void> c3 = CompletableFuture.runAsync(() -> {
            //3:单独查询价格
            BigDecimal price = productFeignClient.getPrice(skuId);
            map.put("price", price);
        }, threadPool);

        CompletableFuture<Void> c4 = c1.thenAcceptAsync(skuInfo -> {
            //4、查询spu中总销售属性 及属性值
            List<SpuSaleAttr> saleAttrAndValeAndChecked = productFeignClient.getSaleAttrAndValeAndChecked(skuId, skuInfo.getSpuId());
            map.put("spuSaleAttrList", saleAttrAndValeAndChecked);
        }, threadPool);

        CompletableFuture<Void> c5 = c1.thenAcceptAsync(skuInfo -> {
            //5：查询页面上 组合与skuId之间关系
            Map<String, String> skuValueIdsMap = productFeignClient.getSkuValueIdsMap(skuInfo.getSpuId());
            map.put("valuesSkuJson", JSONObject.toJSONString(skuValueIdsMap));
        }, threadPool);

        CompletableFuture.runAsync(() ->{
            listFeignClient.hotScore(skuId);
        },threadPool);


        CompletableFuture.allOf(c1,c2,c3,c4,c5).join();
        return map;
    }
}
